/**
 * @Authors
 * Avinash Sridhar	G Number: G00861300
 * Martin Nguyen	G Number: G00396532
 * Jitin Krishnan	G Number: G00834757
 * 
 * @Course
 * CS571 Operating Systems Fall 2013
 * Assignment 3
 * Due: Dec 2, 2013 
 * Instructor: Hakan Aydin
 * 
 * Filename: CriticalSectionService.java
 * 
 **/

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Date;


public class CriticalSectionService extends Thread{

	private RMIServer mServer;
	
	public CriticalSectionService(RMIServer server) {

		mServer = server;
	}

	@Override
	public void run() {
		
		try {
			System.out.println("-----CS Thread-----");
			sleep((long) mServer.ProcessingDelay);
			
			if (mServer.getmHasRequests())
			{
				//--------------CRITICAL SECTION-----------------
				System.out.println(mServer.getmCurrDeptModule().mName + " entering Critical section at " + new Timestamp(new Date().getTime()) + "*****");
				
				mServer.setmHasToken(true); 	//should awaken the sleeping main thread in either lookup or reserve
				
				sleep((long) mServer.CriticalSectionDelay);
				
				System.out.println(mServer.getmCurrDeptModule().mName + " exiting Critical section at " + new Timestamp(new Date().getTime()) + "*****");
				//--------------END CRITICAL SECTION-------------
				mServer.setmHasToken(false);
			}
	
			//pass off the token CLOCKWISE (TO THE RIGHT NEIGHBOR)
			if(!mServer.getmLeftDeptModule().mName.equals(mServer.getmCurrDeptModule().mName)	&&
					 !mServer.getmRightDeptModule().mName.equals(mServer.getmCurrDeptModule().mName))
			WriteToPort("TOKEN", mServer.getmRightDeptModule());

			System.out.println("--------------------");
		} catch (InterruptedException e)
		{
			
		}
	
	}

	
	public void WriteToPort(String stringToWrite, DeptModuleInfo dept)
	{
    	try {
    		InetAddress server_addr = InetAddress.getByName("localhost");
    		
    		Socket client = new Socket(server_addr, dept.mTokenSocketPortNumber);
			PrintWriter Writer = new PrintWriter(client.getOutputStream(), true);
			Writer.println(stringToWrite);
			
			System.out.println(mServer.getmCurrDeptModule().mName + " > " + stringToWrite + " > " + dept.mName + " at " + System.currentTimeMillis());
			
			client.close();
			Writer.close();
    		
    	} catch (IOException e) 
    	{ 
    		//e.printStackTrace();
    	}
	}
}
